<template>
  <div class="video-detail-container">
    <el-row :gutter="20">
      <!-- 左侧视频播放和信息区域 -->
      <el-col :xs="24" :md="18">
        <div v-if="loadingVideo" class="loading-placeholder player-placeholder">
          <el-skeleton animated>
            <template #template>
              <el-skeleton-item variant="image" style="width: 100%; height: 400px;" />
              <div style="padding: 14px;">
                <el-skeleton-item variant="h1" style="width: 70%; margin-bottom: 10px;" />
                <el-skeleton-item variant="text" style="margin-right: 16px;" />
                <el-skeleton-item variant="text" style="width: 30%;" />
              </div>
            </template>
          </el-skeleton>
        </div>
        <div v-else-if="video" class="video-player-section">
          <!-- 使用 VideoPlayer 组件，并传递视频 URL 和格式选项 -->          
          <video-player 
            :video-url="selectedFormat?.url"
            :preview-thumbnails="video?.previewThumbnails"
            :preview-vtt="video?.previewVtt"
            :formats="video?.formats"
            @format-change="handleFormatChange"
          />
          <h1 class="video-title">{{ video.title }}</h1>
          <div class="video-meta">
            <div class="channel-info">
              <router-link :to="`/channel/${video.user?._id}`">
                <el-avatar :size="40" :src="video.user?.avatar">
                  <el-icon><User /></el-icon>
                </el-avatar>
              </router-link>
              <div class="channel-details">
                <router-link :to="`/channel/${video.user?._id}`" class="channel-name">{{ video.user?.username || '未知用户' }}</router-link>
                <span class="subscriber-count">{{ formatSubscribers(video.user?.subscribersCount || 0) }} 订阅者</span>
              </div>
              <el-button
                :type="interactionStatus.isSubscribed ? 'info' : 'danger'"
                round
                @click="toggleSubscription"
                :loading="subscribing"
                v-if="isLoggedIn && currentUser?._id !== video.user?._id"
              >
                {{ interactionStatus.isSubscribed ? '已订阅' : '订阅' }}
              </el-button>
            </div>
            <div class="video-actions">
              <el-button
                :type="interactionStatus.isLiked ? 'primary' : 'default'"
                round
                @click="toggleLikeVideo"
                :loading="likingVideo"
                :disabled="!isLoggedIn"
              >
                <el-icon><Star v-if="!interactionStatus.isLiked" /><StarFilled v-else /></el-icon>
                {{ formatNumber(video.likesCount || 0) }}
              </el-button>
              <el-button round @click="shareVideo"><el-icon><Share /></el-icon> 分享</el-button>
            </div>
          </div>
          <div class="video-description" :class="{ expanded: !descriptionCollapsed }">
            <div class="description-header">
              <span>{{ formatViews(video.views || 0) }} 次观看</span>
              <span>{{ formatDate(video.createdAt) }}</span>
            </div>
            <p class="description-content" ref="descriptionContentRef">
              {{ video.description || '暂无描述' }}
            </p>
            <el-button type="text" v-if="isDescriptionLong" @click="toggleDescription" class="toggle-description-btn">
              {{ descriptionCollapsed ? '展开' : '收起' }}
            </el-button>
          </div>
        </div>
        <el-empty v-else description="视频加载失败或不存在" />

        <!-- 评论区 -->
        <div class="comments-section" v-if="video" style="margin-top: 20px;">
          <h2>{{ totalComments }} 条评论</h2>
          <!-- 添加评论输入框 -->
          <add-comment :targetId="videoId" targetType="video" @comment-added="handleCommentAdded" v-if="isLoggedIn" />
          <div v-else class="login-prompt">请 <router-link to="/login">登录</router-link> 后发表评论</div>

          <!-- 评论列表 -->
          <comment-list
            :comments="comments"
            :loading="loadingComments"
            :hasMore="hasMoreComments"
            @load-more="loadMoreComments"
            @reply-added="handleReplyAdded"
            @comment-updated="handleCommentUpdated"
            @comment-deleted="handleCommentDeleted"
            @like-toggled="handleLikeToggled"
          />
        </div>
      </el-col>

      <!-- 右侧推荐视频区域 -->
      <el-col :xs="24" :md="6">
        <div class="related-videos-section">
          <h3>相关视频</h3>
          <div v-loading="loadingRelated">
            <div v-if="relatedVideos.length === 0 && !loadingRelated" class="empty-state-small">
              <el-empty description="暂无相关视频" :image-size="60" />
            </div>
            <div v-else>
              <related-video-card 
                v-for="relatedVideo in relatedVideos" 
                :key="relatedVideo._id" 
                :video="relatedVideo" 
                @play-directly="playRelatedVideo"
              />
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from '@/services/axios'
import { ElMessage, ElMessageBox } from 'element-plus';
import { Star, StarFilled, Share, User } from '@element-plus/icons-vue';
import { useStore } from 'vuex';
import VideoPlayer from '@/components/VideoPlayer.vue';
import AddComment from '@/components/AddComment.vue';
import CommentList from '@/components/CommentList.vue';
import RelatedVideoCard from '@/components/RelatedVideoCard.vue';
import { formatNumber, formatViews, formatDate, formatSubscribers } from '@/utils/formatters';

const route = useRoute();
const router = useRouter();
const store = useStore();

const videoId = ref(route.params.id);
const video = ref(null);
const loadingVideo = ref(true);

const comments = ref([]);
const loadingComments = ref(false);
const hasMoreComments = ref(true);
const commentsPage = ref(1);
const commentsLimit = 10;
const totalComments = ref(0);

const relatedVideos = ref([]);
const loadingRelated = ref(false);

const interactionStatus = ref({ isLiked: false, isSubscribed: false });
const likingVideo = ref(false);
const subscribing = ref(false);

const descriptionCollapsed = ref(true);
const isDescriptionLong = ref(false);
const descriptionContentRef = ref(null);
const videoPlayerRef = ref(null); // 获取 VideoPlayer 组件的引用

const isLoggedIn = computed(() => store.getters['auth/isAuthenticated']);
const currentUser = computed(() => store.state.auth.user);
const authToken = computed(() => store.getters['auth/token']);

// 获取视频详情
const fetchVideoDetails = async () => {
  if (!videoId.value || videoId.value === 'undefined') {
    console.warn('视频 ID 无效或不可用，重定向到首页');
    ElMessage.error('无效的视频链接');
    router.push('/');
    return;
  }
  
  loadingVideo.value = true;
  console.log('正在获取视频详情，ID:', videoId.value);
  
  try {
    const response = await axios.get(`/api/videos/${videoId.value}`);
    if (!response.data.video) {
      throw new Error('视频不存在');
    }
    
    video.value = response.data.video;
    totalComments.value = video.value.commentsCount || 0;

    // 检查描述是否过长
    await nextTick();
    if (descriptionContentRef.value) {
      const lineHeight = parseInt(window.getComputedStyle(descriptionContentRef.value).lineHeight);
      isDescriptionLong.value = descriptionContentRef.value.scrollHeight > lineHeight * 3;
    }

    // 获取其他相关数据
    await Promise.all([
      fetchComments(true),
      fetchRelatedVideos(),
      isLoggedIn.value && fetchInteractionStatus()
    ]);

  } catch (error) {
    console.error('获取视频详情失败:', error);
    ElMessage.error(error.response?.data?.error || '获取视频详情失败');
    video.value = null;
    router.push('/404');
  } finally {
    loadingVideo.value = false;
  }
};

// 获取评论列表
const fetchComments = async (reset = false) => {
  if (!video.value) return;
  
  if (reset) {
    commentsPage.value = 1;
    comments.value = [];
    hasMoreComments.value = true;
  }
  
  if (!hasMoreComments.value || loadingComments.value) return;
  
  loadingComments.value = true;
  try {
    const response = await axios.get(`/api/videos/${videoId.value}/comments`, {
      params: {
        page: commentsPage.value,
        limit: commentsLimit
      }
    });
    
    const newComments = response.data.comments;
    comments.value = reset ? newComments : [...comments.value, ...newComments];
    hasMoreComments.value = newComments.length === commentsLimit;
    commentsPage.value++;
    
  } catch (error) {
    console.error('获取评论失败:', error);
    ElMessage.error('获取评论失败');
  } finally {
    loadingComments.value = false;
  }
};

// 获取相关视频
const fetchRelatedVideos = async () => {
  if (!video.value) return;
  
  loadingRelated.value = true;
  try {
    // 优先从本地缓存加载相关视频，但确保只在开发环境使用
    // 这样可以保证生产环境下始终获取最新的相关视频数据
    const cachedKey = `related_videos_${video.value._id}`;
    const cachedVideos = localStorage.getItem(cachedKey);
    
    if (import.meta.env.DEV && cachedVideos) {
      try {
        const parsed = JSON.parse(cachedVideos);
        // 验证缓存的数据是否完整包含格式信息
        const isValid = parsed.every(v => v.formats && v.formats.length > 0);
        if (isValid) {
          relatedVideos.value = parsed;
          loadingRelated.value = false;
          console.log('从缓存加载了相关视频', parsed.length);
          return;
        } else {
          console.warn('缓存的相关视频数据不完整，重新获取');
        }
      } catch (e) {
        console.error('解析缓存的相关视频数据失败:', e);
      }
    }
    
    // 如果没有缓存或者缓存无效，则从服务器获取
    const response = await axios.get(`/api/videos/${video.value._id}/related`);
    if (response.data.videos) {
      relatedVideos.value = response.data.videos;
      
      // 验证返回的视频数据是否有格式信息
      const hasFormats = relatedVideos.value.every(v => v.formats && v.formats.length > 0);
      if (!hasFormats) {
        console.warn('部分相关视频缺少格式信息，这可能导致播放问题');
      }
      
      // 在开发环境中缓存结果
      if (import.meta.env.DEV) {
        localStorage.setItem(cachedKey, JSON.stringify(relatedVideos.value));
        // 1小时后过期
        setTimeout(() => localStorage.removeItem(cachedKey), 3600000);
      }
    } else {
      relatedVideos.value = [];
    }
  } catch (error) {
    console.error('获取相关视频失败:', error);
    ElMessage.error('获取相关视频失败');
    relatedVideos.value = [];
  } finally {
    loadingRelated.value = false;
  }
};

// 获取用户交互状态
const fetchInteractionStatus = async () => {
  if (!video.value || !isLoggedIn.value) return;
  
  try {
    const response = await axios.get(`/api/videos/${videoId.value}/interaction`);
    interactionStatus.value = response.data;
  } catch (error) {
    console.error('获取交互状态失败:', error);
  }
};

// 切换点赞状态
const toggleLikeVideo = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录');
    return;
  }
  
  likingVideo.value = true;
  try {
    const response = await axios.post(`/api/videos/${videoId.value}/like`);
    interactionStatus.value.isLiked = response.data.isLiked;
    video.value.likesCount = response.data.likesCount;
  } catch (error) {
    console.error('点赞失败:', error);
    ElMessage.error('操作失败，请稍后重试');
  } finally {
    likingVideo.value = false;
  }
};

// 切换订阅状态
const toggleSubscription = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录');
    return;
  }

  if (!video.value || !video.value.user) {
    console.error('视频或用户信息不可用');
    return;
  }

  subscribing.value = true;
  try {
    // 修复API路径，确保使用完整URL并正确编码用户ID
    const userId = video.value.user._id.toString();
    // 使用encodeURIComponent确保特殊字符被正确编码
    const response = await axios.post(`/api/user/${encodeURIComponent(userId)}/subscribe`);
    console.log('订阅响应:', response.data); // 添加日志
    interactionStatus.value.isSubscribed = response.data.isSubscribed;

    // 根据返回的订阅状态更新订阅数
    if (response.data.isSubscribed) {
      video.value.user.subscribersCount = (video.value.user.subscribersCount || 0) + 1;
    } else {
      video.value.user.subscribersCount = Math.max(0, (video.value.user.subscribersCount || 0) - 1);
    }

  } catch (error) {
    console.error('订阅失败:', error);
    console.log('错误详情:', error.response || error); // 增强错误日志
    ElMessage.error(error.response?.data?.error || '订阅操作失败，请稍后重试');
  } finally {
    subscribing.value = false;
  }
};

// 分享视频
const shareVideo = () => {
  // 复制当前页面链接
  const url = window.location.href;
  navigator.clipboard.writeText(url)
    .then(() => ElMessage.success('链接已复制到剪贴板'))
    .catch(() => ElMessage.error('复制链接失败'));
};

// 切换描述展开/收起
const toggleDescription = () => {
  descriptionCollapsed.value = !descriptionCollapsed.value;
};

// 评论相关事件处理
const handleCommentAdded = (newComment) => {
  comments.value.unshift(newComment);
  totalComments.value++;
};

const handleReplyAdded = (reply) => {
  // 找到父评论并添加回复
  const parentComment = comments.value.find(c => c._id === reply.parentId);
  if (parentComment) {
    if (!parentComment.replies) parentComment.replies = [];
    parentComment.replies.push(reply);
    totalComments.value++;
  }
};

const handleCommentUpdated = (updatedComment) => {
  const index = comments.value.findIndex(c => c._id === updatedComment._id);
  if (index !== -1) {
    comments.value[index] = { ...comments.value[index], ...updatedComment };
  }
};

const handleCommentDeleted = (commentId) => {
  comments.value = comments.value.filter(c => c._id !== commentId);
  totalComments.value--;
};

const handleLikeToggled = (commentId, newLikesCount) => {
  const comment = comments.value.find(c => c._id === commentId);
  if (comment) {
    comment.likesCount = newLikesCount;
  }
};

// 监听路由参数变化 - 改进处理逻辑
watch(() => route.params.id, (newId, oldId) => {
  if (newId && newId !== videoId.value) {
    console.log(`路由参数变化: ${oldId} -> ${newId}`);
    videoId.value = newId;
    fetchVideoDetails();
  } else if (!newId) {
    console.warn('路由参数中没有视频 ID');
    router.push('/');
  }
}, { immediate: true });

// 添加对浏览器后退事件的监听
onMounted(() => {
  if (videoId.value) {
    fetchVideoDetails();
  }
  
  // 添加 popstate 事件监听，处理浏览器前进/后退按钮
  window.addEventListener('popstate', handlePopState);
});

// 组件卸载时清理
onUnmounted(() => {
  console.log('VideoDetailView 组件卸载，执行清理');
  if (videoPlayerRef.value && typeof videoPlayerRef.value.cleanup === 'function') {
    videoPlayerRef.value.cleanup(); // 调用 VideoPlayer 的清理方法
  }
  video.value = null;
  comments.value = [];
  relatedVideos.value = [];
  
  // 移除事件监听器
  window.removeEventListener('popstate', handlePopState);
});

// 处理浏览器历史导航事件
const handlePopState = (event) => {
  console.log('历史导航事件触发:', event.state);
  
  const currentPath = window.location.pathname;
  
  // 区分不同的路径类型并相应处理
  if (currentPath === '/') {
    // 如果返回到首页，完全由浏览器处理
    console.log('已返回到首页，由浏览器处理');
    return;
  }
  
  const videoIdMatch = currentPath.match(/\/video\/([^\/]+)/);
  if (videoIdMatch) {
    // 仍然在视频页面，但可能是不同的视频
    const newVideoId = videoIdMatch[1];
    console.log('视频导航:', videoId.value, '->', newVideoId);
    
    if (newVideoId !== videoId.value) {
      // 不同视频，加载新视频
      videoId.value = newVideoId;
      fetchVideoDetails();
    }
  } else {
    // 其他页面路径，让路由系统处理
    console.log('导航到其他页面:', currentPath);
    const relativePath = currentPath || '/';
    router.replace(relativePath).catch(err => {
      console.error('导航失败:', err);
    });
  }
};

// 视频格式选择
const selectedFormat = ref(null);

// 初始化选择默认格式
const initDefaultFormat = () => {
  if (video.value?.formats?.length > 0) {
    // 默认选择最高质量的格式
    selectedFormat.value = video.value.formats.reduce((prev, curr) => {
      return (!prev || curr.height > prev.height) ? curr : prev;
    }, null);
    
    console.log('已初始化视频格式:', selectedFormat.value?.url);
  } else {
    console.warn('视频没有可用格式');
    selectedFormat.value = null;
  }
};

// 处理格式切换
const handleFormatChange = (format) => {
  selectedFormat.value = format;
  console.log('切换视频格式:', format);
};

// 在获取视频详情后初始化格式
watch(() => video.value, (newVideo) => {
  if (newVideo) {
    initDefaultFormat();
  }
}, { immediate: true });

// 直接播放相关视频
const playRelatedVideo = (relatedVideo) => {
  if (!relatedVideo) {
    ElMessage.error('相关视频数据无效');
    return;
  }
  
  console.log('播放相关视频:', relatedVideo.title);
  
  if (!relatedVideo.formats || relatedVideo.formats.length === 0) {
    ElMessage.error('视频格式不可用，无法播放');
    return;
  }
  
  // 在加载新视频前先清理当前播放器资源
  if (videoPlayerRef.value && typeof videoPlayerRef.value.cleanup === 'function') {
    videoPlayerRef.value.cleanup();
    console.log('已清理当前视频播放器资源');
  }
  
  // 暂存当前视频ID用于历史记录
  const currentVideoId = videoId.value;
  
  // 更新视频数据
  video.value = relatedVideo;
  videoId.value = relatedVideo._id;
  
  // 立即初始化视频格式
  if (relatedVideo.formats && relatedVideo.formats.length > 0) {
    selectedFormat.value = relatedVideo.formats.reduce((prev, curr) => {
      return (!prev || curr.height > prev.height) ? curr : prev;
    }, null);
    console.log('已选择相关视频格式:', selectedFormat.value?.url);
  }
  
  // 记录浏览历史 - 使用replaceState而不是pushState
  // 这样在播放相关视频后点击返回会直接回到最初的页面，而不是卡在相关视频列表中
  const newUrl = `/video/${relatedVideo._id}`;
  try {
    // 使用更详细的状态对象
    const historyState = { 
      page: 'video',
      videoId: relatedVideo._id, 
      previousVideoId: currentVideoId,
      timestamp: Date.now()
    };
    
    window.history.replaceState(historyState, '', newUrl);
    console.log('历史状态已更新:', historyState);
  } catch (err) {
    console.error('更新历史状态失败:', err);
  }
  
  // 更新视频观看次数
  updateVideoView(relatedVideo._id);
  
  // 获取用户交互状态和相关数据
  if (isLoggedIn.value) {
    fetchInteractionStatus();
  }
  
  // 更新评论和相关视频 - 使用Promise.all优化并发请求
  Promise.all([
    fetchComments(true),
    new Promise(resolve => setTimeout(() => {
      fetchRelatedVideos().then(resolve);
    }, 300))
  ]).catch(err => {
    console.error('获取相关数据失败:', err);
  });
};

// 增加视频观看次数
const updateVideoView = async (id) => {
  try {
    await axios.post(`/api/videos/${id}/view`);
  } catch (error) {
    console.error('更新观看次数失败:', error);
  }
};
</script>

<style scoped>
.video-detail-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.loading-placeholder.player-placeholder {
    height: 400px; /* 根据播放器大致高度设置 */
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f0f2f5;
    border-radius: 8px;
}

.video-player-section {
  margin-bottom: 20px;
}

.video-title {
  font-size: 22px;
  font-weight: 600;
  margin: 15px 0 10px 0;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap; /* 允许换行 */
  gap: 10px;
}

.channel-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.channel-details {
  display: flex;
  flex-direction: column;
}

.channel-name {
  font-weight: 500;
  color: #303133;
  text-decoration: none;
}
.channel-name:hover {
    text-decoration: underline;
}

.subscriber-count {
  font-size: 12px;
  color: #606266;
}

.video-actions {
  display: flex;
  gap: 10px;
}

.video-actions .el-button .el-icon {
    margin-right: 5px;
}

.video-description {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.6;
  color: #303133;
  margin-top: 10px;
  cursor: pointer;
  transition: max-height 0.3s ease-out;
  overflow: hidden;
}

.video-description.expanded {
    cursor: default;
}

.description-header {
  font-size: 13px;
  color: #606266;
  margin-bottom: 10px;
}

.description-header span + span {
  margin-left: 15px;
}

.description-content {
  white-space: pre-wrap; /* 保留换行 */
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3; /* 默认显示3行 */
  max-height: calc(1.6em * 3); /* 估算3行高度 */
  transition: max-height 0.3s ease-out;
}

.video-description.expanded .description-content {
    -webkit-line-clamp: unset;
    max-height: 1000px; /* 一个足够大的值 */
}

.toggle-description-btn {
    margin-top: 5px;
    padding: 0;
    height: auto;
}

.comments-section {
  margin-top: 30px;
}

.comments-section h2 {
  font-size: 18px;
  margin-bottom: 20px;
}

.login-prompt {
    margin: 20px 0;
    padding: 15px;
    background-color: #f0f2f5;
    border-radius: 4px;
    text-align: center;
    font-size: 14px;
}
.login-prompt a {
    color: #409eff;
    text-decoration: none;
}
.login-prompt a:hover {
    text-decoration: underline;
}

.related-videos-section h3 {
  font-size: 18px;
  margin-bottom: 15px;
}

.empty-state-small .el-empty__image {
    width: 60px;
}
.empty-state-small .el-empty__description {
    margin-top: 8px;
}

</style>

@media (max-width: 768px) {
  .video-detail-container .el-row {
    margin-left: 0;
    margin-right: 0;
  }
  .video-detail-container .el-col {
    padding-left: 100px;
    padding-right: 0px;
  }
  .video-detail-container {
    padding: 10px;
  }
  .video-player-section,
  .related-videos-section {
    width: 100%;
    margin-bottom: 20px;
  }
}